<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.0.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.0.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.0.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.0.4">


  <link rel="mask-icon" href="/images/logo.svg?v=6.0.4" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.0.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  
  <meta name="keywords" content="监控," />


<meta name="description" content="设计思路可以在一个网站/App项目设置多个HTTP监控任务，将监控任务放到延时队列，其中HTTP监控任务需要配置请求URL，请求方式GET，匹配内容等。后台运行队列任务，请求监控任务URL生成请求快照，根据请求快照和监控任务设定的匹配方式对比，若不匹配则则通过邮件等方式发送通知。 添加任务：">
<meta name="keywords" content="监控">
<meta property="og:type" content="article">
<meta property="og:title" content="使用laravel开发网站监控程序">
<meta property="og:url" content="http://blog.yunshu168.com/posts/6ca2fd60.html">
<meta property="og:site_name" content="树下千云">
<meta property="og:description" content="设计思路可以在一个网站/App项目设置多个HTTP监控任务，将监控任务放到延时队列，其中HTTP监控任务需要配置请求URL，请求方式GET，匹配内容等。后台运行队列任务，请求监控任务URL生成请求快照，根据请求快照和监控任务设定的匹配方式对比，若不匹配则则通过邮件等方式发送通知。 添加任务：">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/006tNbRwgy1g9kuc4cmy8j30wm0c0jru.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/006tNbRwgy1g9kud40424j30yi0u0wj2.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/006tNbRwgy1g9kueku6pjj30om0rwgo0.jpg">
<meta property="og:updated_time" content="2019-12-04T11:25:35.754Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="使用laravel开发网站监控程序">
<meta name="twitter:description" content="设计思路可以在一个网站/App项目设置多个HTTP监控任务，将监控任务放到延时队列，其中HTTP监控任务需要配置请求URL，请求方式GET，匹配内容等。后台运行队列任务，请求监控任务URL生成请求快照，根据请求快照和监控任务设定的匹配方式对比，若不匹配则则通过邮件等方式发送通知。 添加任务：">
<meta name="twitter:image" content="https://tva1.sinaimg.cn/large/006tNbRwgy1g9kuc4cmy8j30wm0c0jru.jpg">






  <link rel="canonical" href="http://blog.yunshu168.com/posts/6ca2fd60.html"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>
  <title>使用laravel开发网站监控程序 | 树下千云</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?f8a99180bb75f49a4b2206cab6e25c50";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <!-- <div class="headband"></div>
<a href="https://github.com/yunshu2009"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a> -->
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">树下千云</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>


  



 </div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.yunshu168.com/posts/6ca2fd60.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="云舒">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="树下千云">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">使用laravel开发网站监控程序</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <!--<span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>-->
              
                <!--<span class="post-meta-item-text">发表于</span>-->
              
              <!--<time title="创建于" itemprop="dateCreated datePublished" datetime="2018-12-04T16:07:03+08:00">2018-12-04</time>-->
            

            
            

            
          </span>

          

          
            
          

          
          

          


          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="设计思路"><a href="#设计思路" class="headerlink" title="设计思路"></a>设计思路</h3><p>可以在一个网站/App项目设置多个HTTP监控任务，将监控任务放到延时队列，其中HTTP监控任务需要配置请求URL，请求方式GET，匹配内容等。后台运行队列任务，请求监控任务URL生成请求快照，根据请求快照和监控任务设定的匹配方式对比，若不匹配则则通过邮件等方式发送通知。</p>
<p>添加任务：<br><img src="https://tva1.sinaimg.cn/large/006tNbRwgy1g9kuc4cmy8j30wm0c0jru.jpg" alt=""><br><a id="more"></a><br>添加监控：<br><img src="https://tva1.sinaimg.cn/large/006tNbRwgy1g9kud40424j30yi0u0wj2.jpg" alt=""></p>
<p>生成的快照：<br><img src="https://tva1.sinaimg.cn/large/006tNbRwgy1g9kueku6pjj30om0rwgo0.jpg" alt=""></p>
<h3 id="程序实现"><a href="#程序实现" class="headerlink" title="程序实现"></a>程序实现</h3><h4 id="数据库表设计"><a href="#数据库表设计" class="headerlink" title="数据库表设计"></a>数据库表设计</h4><p>使用了php laravel框架的migration自动生成表结构：</p>
<p>project表：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Schema::create(<span class="string">'projects'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(Blueprint $table)</span> </span>&#123;</span><br><span class="line">    $table-&gt;increments(<span class="string">'id'</span>);</span><br><span class="line"> $table-&gt;unsignedInteger(<span class="string">'user_id'</span>);</span><br><span class="line">    $table-&gt;string(<span class="string">'title'</span>);</span><br><span class="line">    $table-&gt;timestamps();</span><br><span class="line"></span><br><span class="line"> $table-&gt;foreign(<span class="string">'user_id'</span>)-&gt;references(<span class="string">'id'</span>)-&gt;on(<span class="string">'users'</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></p>
<p>监控表<code>monitors</code>：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">Schema::create(<span class="string">'monitors'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(Blueprint $table)</span> </span>&#123;</span><br><span class="line">         $table-&gt;increments(<span class="string">'id'</span>);</span><br><span class="line">         $table-&gt;unsignedInteger(<span class="string">'project_id'</span>);</span><br><span class="line">         $table-&gt;string(<span class="string">'title'</span>);</span><br><span class="line">         $table-&gt;text(<span class="string">'request_url'</span>);</span><br><span class="line">         $table-&gt;text(<span class="string">'request_method'</span>);</span><br><span class="line">         $table-&gt;text(<span class="string">'request_headers'</span>)-&gt;nullable(); <span class="comment">// 不包含首行</span></span><br><span class="line">         $table-&gt;text(<span class="string">'request_body'</span>)-&gt;nullable();</span><br><span class="line"></span><br><span class="line">         $table-&gt;boolean(<span class="string">'request_nobody'</span>)-&gt;default(<span class="keyword">false</span>); <span class="comment">// 是否不请求body</span></span><br><span class="line">         $table-&gt;boolean(<span class="string">'is_enable'</span>)-&gt;default(<span class="keyword">true</span>); <span class="comment">// 是否启用监控</span></span><br><span class="line">         $table-&gt;boolean(<span class="string">'is_public'</span>)-&gt;default(<span class="keyword">false</span>); <span class="comment">// 是否启用监控</span></span><br><span class="line">         $table-&gt;boolean(<span class="string">'no_notice_error'</span>)-&gt;default(<span class="keyword">false</span>); <span class="comment">// 是否不通知错误</span></span><br><span class="line">         $table-&gt;boolean(<span class="string">'no_notice_match'</span>)-&gt;default(<span class="keyword">false</span>); <span class="comment">// 是否不通知匹配</span></span><br><span class="line"></span><br><span class="line">         $table-&gt;unsignedInteger(<span class="string">'interval_normal'</span>); <span class="comment">// 未匹配也无错误的情况下间隔秒数</span></span><br><span class="line">         $table-&gt;unsignedInteger(<span class="string">'interval_match'</span>); <span class="comment">// 匹配的情况下间隔秒数</span></span><br><span class="line">         $table-&gt;unsignedInteger(<span class="string">'interval_error'</span>); <span class="comment">// 出错的情况下间隔秒数</span></span><br><span class="line"></span><br><span class="line">      $table-&gt;boolean(<span class="string">'request_follow_location'</span>)-&gt;default(<span class="keyword">true</span>); <span class="comment">// 是否跟随跳转</span></span><br><span class="line"></span><br><span class="line">         $table-&gt;string(<span class="string">'match_type'</span>); <span class="comment">// include / http_status_code / timeout</span></span><br><span class="line">         $table-&gt;boolean(<span class="string">'match_reverse'</span>)-&gt;default(<span class="keyword">false</span>); <span class="comment">// 相反匹配，例如timeout 翻转的话，就是如果响应时间快于x毫秒，则通知</span></span><br><span class="line">         $table-&gt;string(<span class="string">'match_content'</span>); <span class="comment">// 内容或状态吗</span></span><br><span class="line">         $table-&gt;timestamps();</span><br><span class="line"></span><br><span class="line">         $table-&gt;foreign(<span class="string">'project_id'</span>)-&gt;references(<span class="string">'id'</span>)-&gt;on(<span class="string">'projects'</span>);</span><br><span class="line">     &#125;);</span><br></pre></td></tr></table></figure></p>
<p>快照表:</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">Schema::create(<span class="string">'snapshots'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(Blueprint $table)</span> </span>&#123;</span><br><span class="line">      $table-&gt;increments(<span class="string">'id'</span>);</span><br><span class="line">      $table-&gt;unsignedInteger(<span class="string">'monitor_id'</span>);</span><br><span class="line">      $table-&gt;boolean(<span class="string">'is_match'</span>)-&gt;default(<span class="keyword">false</span>); <span class="comment">// 是否属于异常通知，例如包含内容已经找到，is_error为1的话，is_notice必定为1，因为错误肯定要提示的。</span></span><br><span class="line">      $table-&gt;boolean(<span class="string">'is_error'</span>)-&gt;default(<span class="keyword">false</span>); <span class="comment">// 是否请求错误，没有得到响应头的情况，都属于此类，包含 dns解析错误、TCP连接无法建立/响应前中断、得到的响应不符合HTTP规范等</span></span><br><span class="line">      $table-&gt;boolean(<span class="string">'is_done'</span>)-&gt;default(<span class="keyword">false</span>);</span><br><span class="line"></span><br><span class="line">      $table-&gt;text(<span class="string">'error_message'</span>)-&gt;nullable(); <span class="comment">// 自定义拼合文本，人类可读</span></span><br><span class="line">      $table-&gt;string(<span class="string">'http_status_code'</span>)-&gt;nullable();</span><br><span class="line">      $table-&gt;unsignedInteger(<span class="string">'header_size'</span>)-&gt;nullable(); <span class="comment">// 包含首行，如果有跳转，将包含多次的header。</span></span><br><span class="line">      $table-&gt;string(<span class="string">'response_path'</span>)-&gt;nullable(); <span class="comment">// 包含首行，如果有跳转，将包含多次的header。</span></span><br><span class="line"></span><br><span class="line">      $table-&gt;unsignedInteger(<span class="string">'time_total'</span>)-&gt;default(<span class="number">0</span>); <span class="comment">// 从dns解析，到获取到最后一字节的时间</span></span><br><span class="line">      $table-&gt;unsignedInteger(<span class="string">'time_dns'</span>)-&gt;default(<span class="number">0</span>);</span><br><span class="line">      $table-&gt;unsignedInteger(<span class="string">'time_connection'</span>)-&gt;default(<span class="number">0</span>);</span><br><span class="line">      $table-&gt;unsignedInteger(<span class="string">'time_transport'</span>)-&gt;default(<span class="number">0</span>);</span><br><span class="line">      <span class="comment">// 暂未设计“已通知”字段，因为，通知一旦发起，是保证成功的，即使未成功，也是放在队列中和失败队列任务中。暂不考虑永远失败的情况。</span></span><br><span class="line"></span><br><span class="line">      <span class="comment">// todo 其实下面这一段数据，应该放到检查记录里，而不是快照中。但是目前一次检查只有一个快照的情况下，先放这里吧。</span></span><br><span class="line">      $table-&gt;boolean(<span class="string">'is_notice'</span>)-&gt;default(<span class="keyword">false</span>);</span><br><span class="line">      $table-&gt;unsignedInteger(<span class="string">'status_level'</span>)-&gt;default(<span class="number">0</span>);</span><br><span class="line">      $table-&gt;string(<span class="string">'status_text'</span>)-&gt;nullable();</span><br><span class="line">      $table-&gt;text(<span class="string">'status_message'</span>)-&gt;nullable();</span><br><span class="line"></span><br><span class="line">      $table-&gt;timestamps();</span><br><span class="line"></span><br><span class="line">      $table-&gt;index([<span class="string">'monitor_id'</span>, <span class="string">'is_done'</span>, <span class="string">'created_at'</span>]);</span><br><span class="line"></span><br><span class="line">      $table-&gt;foreign(<span class="string">'monitor_id'</span>)-&gt;references(<span class="string">'id'</span>)-&gt;on(<span class="string">'monitors'</span>);</span><br><span class="line">  &#125;);</span><br></pre></td></tr></table></figure>
<h4 id="编码实现"><a href="#编码实现" class="headerlink" title="编码实现"></a>编码实现</h4><p>主要代码：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"><span class="keyword">namespace</span> <span class="title">App</span>\<span class="title">Service</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">use</span> <span class="title">App</span>\<span class="title">Jobs</span>\<span class="title">MonitorJob</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">App</span>\<span class="title">Mail</span>\<span class="title">MonitorNotice</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">App</span>\<span class="title">Monitor</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">App</span>\<span class="title">Project</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">App</span>\<span class="title">Snapshot</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">App</span>\<span class="title">User</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">Carbon</span>\<span class="title">Carbon</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">Illuminate</span>\<span class="title">Database</span>\<span class="title">Eloquent</span>\<span class="title">ModelNotFoundException</span>;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MonitorService</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    .</span><br><span class="line">    <span class="comment">// 使用php artisan monitor 在 MonitorCommand 中调用 runAllMonitor 「MonitorService::runAllMonitor」</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">runAllMonitor</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $jobs = Monitor::all();</span><br><span class="line">        <span class="keyword">foreach</span> ($jobs <span class="keyword">as</span> $job) &#123;</span><br><span class="line">            <span class="keyword">self</span>::joinQueue($job);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 将一个监控任务加入列队，会自动设置延迟</span></span><br><span class="line"><span class="comment">     * 注意：此方法会被MonitorJob递归调用</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> Monitor $monitor</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> void</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">joinQueue</span><span class="params">(Monitor $monitor)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        $interval = $monitor-&gt;interval_normal;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            $lastSnapshot = $monitor-&gt;lastSnapshot();</span><br><span class="line">            <span class="keyword">if</span> ($lastSnapshot-&gt;is_error) &#123;</span><br><span class="line">                $interval = $monitor-&gt;interval_error;</span><br><span class="line">            &#125; <span class="keyword">elseif</span> ($lastSnapshot-&gt;is_match) &#123;</span><br><span class="line">                $interval = $monitor-&gt;interval_match;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ModelNotFoundException $e) &#123;</span><br><span class="line">	        <span class="keyword">if</span> ($monitor-&gt;is_enable)&#123;</span><br><span class="line">		        <span class="comment">// 第一次就立刻运行吧</span></span><br><span class="line">		        $interval = <span class="number">0</span>;</span><br><span class="line">	        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">	        	<span class="comment">// 未启用的，1分钟后再运行。</span></span><br><span class="line">		        $interval = <span class="number">60</span>;</span><br><span class="line">	        &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        $time = Carbon::now()-&gt;addSecond($interval);</span><br><span class="line"></span><br><span class="line">				<span class="comment">// 分为监控任务</span></span><br><span class="line">        dispatch((<span class="keyword">new</span> MonitorJob($monitor))-&gt;delay($time)-&gt;onQueue(<span class="string">'monitor'</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 执行一个监控，返回一个监控快照</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> Monitor $monitor</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> array</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">request</span><span class="params">(Monitor $monitor)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">	    \MonitorLog::debug(<span class="string">"执行HTTP请求，监控ID[&#123;$monitor-&gt;id&#125;]"</span>);</span><br><span class="line">        $curlHandle = curl_init();</span><br><span class="line"></span><br><span class="line">        curl_setopt($curlHandle, CURLOPT_SAFE_UPLOAD, <span class="keyword">true</span>); <span class="comment">// 禁止body中使用@上传文件</span></span><br><span class="line">        curl_setopt($curlHandle, CURLOPT_FORBID_REUSE, <span class="keyword">true</span>); <span class="comment">// 不重用TCP连接</span></span><br><span class="line">        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, <span class="keyword">true</span>); <span class="comment">// 返回数据，不输出</span></span><br><span class="line">        curl_setopt($curlHandle, CURLOPT_HEADER, <span class="keyword">true</span>); <span class="comment">// 输出header</span></span><br><span class="line">        curl_setopt($curlHandle, CURLOPT_FOLLOWLOCATION, $monitor-&gt;request_follow_location); <span class="comment">// 跟随跳转</span></span><br><span class="line">        curl_setopt($curlHandle, CURLOPT_MAXREDIRS, <span class="number">5</span>); <span class="comment">// 跳转次数</span></span><br><span class="line"></span><br><span class="line">        curl_setopt($curlHandle, CURLOPT_URL, $monitor-&gt;request_url);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> ($monitor-&gt;request_nobody) &#123;</span><br><span class="line">            curl_setopt($curlHandle, CURLOPT_NOBODY, <span class="keyword">true</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, $monitor-&gt;request_method);</span><br><span class="line">        <span class="keyword">if</span> ($monitor-&gt;request_method != <span class="string">"GET"</span>) &#123;</span><br><span class="line">            curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $monitor-&gt;request_body);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// CURLOPT_AUTOREFERER 重定向时，自动设置 header 中的Referer:信息。</span></span><br><span class="line">        <span class="comment">// CURLOPT_CONNECT_ONLY 仅连接</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 最大60秒超时</span></span><br><span class="line">        curl_setopt($curlHandle, CURLOPT_TIMEOUT, <span class="number">30</span>);</span><br><span class="line"></span><br><span class="line">        $response = curl_exec($curlHandle);</span><br><span class="line"></span><br><span class="line">        $curlInfo = curl_getinfo($curlHandle);</span><br><span class="line"></span><br><span class="line">        $curlErrorNo = curl_errno($curlHandle);</span><br><span class="line">        $curlErrorMessage = curl_error($curlHandle);</span><br><span class="line"></span><br><span class="line">        curl_close($curlHandle);</span><br><span class="line"></span><br><span class="line">        $curlInfo[<span class="string">'response'</span>] = $response;</span><br><span class="line">        $curlInfo[<span class="string">'curl_error_no'</span>] = $curlErrorNo;</span><br><span class="line">        $curlInfo[<span class="string">'curl_error_message'</span>] = $curlErrorMessage;</span><br><span class="line"></span><br><span class="line">	    \MonitorLog::debug(<span class="string">"HTTP请求完成，监控ID[&#123;$monitor-&gt;id&#125;]"</span>);</span><br><span class="line">        <span class="keyword">return</span> $curlInfo;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> $snapshot Snapshot</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> $requestResult array</span></span><br><span class="line"><span class="comment">	 *</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">storeSnapshot</span><span class="params">($snapshot, $requestResult)</span></span>&#123;</span><br><span class="line">        $userId = $snapshot-&gt;monitor-&gt;project-&gt;user-&gt;id;</span><br><span class="line">        $snapshot-&gt;header_size = $requestResult[<span class="string">'header_size'</span>];</span><br><span class="line">        $snapshot-&gt;response_path = $snapshot-&gt;storeSnapshotResponse($userId, $requestResult[<span class="string">'response'</span>]);</span><br><span class="line">	    $snapshot-&gt;http_status_code = $requestResult[<span class="string">'http_code'</span>];</span><br><span class="line"></span><br><span class="line">	    $snapshot-&gt;time_total = bcmul($requestResult[<span class="string">'total_time'</span>], <span class="number">1000</span>, <span class="number">0</span>);</span><br><span class="line">	    $snapshot-&gt;time_dns = bcmul($requestResult[<span class="string">'namelookup_time'</span>], <span class="number">1000</span>, <span class="number">0</span>);</span><br><span class="line">	    $snapshot-&gt;time_connection = bcmul($requestResult[<span class="string">'connect_time'</span>], <span class="number">1000</span>, <span class="number">0</span>);</span><br><span class="line">	    $snapshot-&gt;time_transport = bcmul($requestResult[<span class="string">'pretransfer_time'</span>], <span class="number">1000</span>, <span class="number">0</span>);</span><br><span class="line">	    $snapshot-&gt;error_message = <span class="string">""</span>;</span><br><span class="line">	    $snapshot-&gt;is_error = <span class="keyword">false</span>;</span><br><span class="line">	    $snapshot-&gt;is_match = <span class="keyword">false</span>;</span><br><span class="line"></span><br><span class="line">	    $curlErrorNo = $requestResult[<span class="string">'curl_error_no'</span>];</span><br><span class="line">	    $curlErrorMessage = $requestResult[<span class="string">'curl_error_message'</span>];</span><br><span class="line"></span><br><span class="line">	    <span class="keyword">if</span> ($curlErrorNo !== <span class="number">0</span>) &#123;</span><br><span class="line">		    $snapshot-&gt;is_error = <span class="keyword">true</span>;</span><br><span class="line">		    $snapshot-&gt;error_message = <span class="string">"curl error[$curlErrorNo]: "</span> . $curlErrorMessage;</span><br><span class="line">            $snapshot-&gt;status_message = $snapshot-&gt;error_message;</span><br><span class="line">	    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">		    $matcher = $snapshot-&gt;getMatcher();</span><br><span class="line">		    <span class="comment">/** <span class="doctag">@var</span> $matcher Monitor\Match\MatchBase */</span></span><br><span class="line">		    $snapshot-&gt;is_match = $matcher-&gt;isMatch();</span><br><span class="line">		    <span class="keyword">if</span> ($snapshot-&gt;is_match)&#123;</span><br><span class="line">                $snapshot-&gt;status_message = $matcher-&gt;getMessage();</span><br><span class="line">            &#125;</span><br><span class="line">	    &#125;</span><br><span class="line"></span><br><span class="line">        $snapshot-&gt;is_notice = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 取出上一个快照，判断是否变化，如果没变化，就直接return了</span></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">/** <span class="doctag">@var</span> Snapshot $perSnapshot */</span></span><br><span class="line">            $perSnapshot = Snapshot::whereMonitorId($snapshot-&gt;monitor_id)-&gt;whereIsDone(<span class="number">1</span>)-&gt;where(<span class="string">'id'</span>, <span class="string">'&lt;'</span>, $snapshot-&gt;id)-&gt;orderBy(<span class="string">'id'</span>, <span class="string">'desc'</span>)-&gt;firstOrFail();</span><br><span class="line">            <span class="keyword">if</span> ($perSnapshot-&gt;is_match == $snapshot-&gt;is_match &amp;&amp; $perSnapshot-&gt;is_error == $snapshot-&gt;is_error) &#123;</span><br><span class="line">                <span class="comment">// 状态未变，所以不通知</span></span><br><span class="line">                $snapshot-&gt;is_notice = <span class="keyword">false</span>;</span><br><span class="line">                <span class="keyword">if</span> (!$snapshot-&gt;is_match &amp;&amp; !$snapshot-&gt;is_error) &#123;</span><br><span class="line">                    $snapshot-&gt;status_text = <span class="string">"未匹配"</span>;</span><br><span class="line">                    $snapshot-&gt;status_level = <span class="number">0</span>;</span><br><span class="line">                &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                    <span class="comment">// 如果匹配状态没变化，且错误状态没变化，就不通知</span></span><br><span class="line">                    $snapshot-&gt;status_text = $perSnapshot-&gt;status_text;</span><br><span class="line">                    $snapshot-&gt;status_level = $perSnapshot-&gt;status_level;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ModelNotFoundException $e) &#123;</span><br><span class="line">            <span class="comment">// 如果第一次，且没有匹配也没错误，就不通知</span></span><br><span class="line">            <span class="keyword">if</span> (!$snapshot-&gt;is_match &amp;&amp; !$snapshot-&gt;is_error) &#123;</span><br><span class="line">                $snapshot-&gt;is_notice = <span class="keyword">false</span>;</span><br><span class="line">                $snapshot-&gt;status_text = <span class="string">"New"</span>;</span><br><span class="line">                $snapshot-&gt;status_level = <span class="number">0</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> ($snapshot-&gt;is_notice !== <span class="keyword">false</span>)&#123;</span><br><span class="line">            <span class="comment">// 就4种状态</span></span><br><span class="line">            <span class="comment">// 常态 - 未匹配</span></span><br><span class="line">            <span class="comment">// 1 错误</span></span><br><span class="line">            <span class="comment">// 2 匹配命中 如果错误，肯定不匹配</span></span><br><span class="line">            <span class="comment">// 3 匹配恢复</span></span><br><span class="line">            <span class="comment">// 不存在的 上次命中，这次错误恢复，因为上次错误，上次就肯定是未匹配，这次不可能匹配恢复</span></span><br><span class="line">            <span class="comment">// 外加几种复合状态</span></span><br><span class="line">            <span class="comment">// 4 错误恢复，即上次错误，这次正常且未匹配，就通知错误恢复</span></span><br><span class="line">            <span class="comment">// 5 错误恢复匹配，即上次错误，这次错误恢复且匹配，就通知匹配</span></span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (!$snapshot-&gt;is_error &amp;&amp; !$snapshot-&gt;is_match) &#123;</span><br><span class="line">                <span class="keyword">if</span> ($perSnapshot-&gt;is_error)&#123;</span><br><span class="line">                    <span class="comment">// 4</span></span><br><span class="line">                    $snapshot-&gt;status_text = <span class="string">"错误恢复"</span>;</span><br><span class="line">                    $snapshot-&gt;status_level = <span class="number">1</span>;</span><br><span class="line">                    $snapshot-&gt;status_message = <span class="string">"之前的错误已经消失，现在是正常未匹配状态"</span>;</span><br><span class="line">                &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                    <span class="comment">// 3</span></span><br><span class="line">                    $snapshot-&gt;status_text = <span class="string">"未匹配"</span>;</span><br><span class="line">                    $snapshot-&gt;status_level = <span class="number">0</span>;</span><br><span class="line">                    $snapshot-&gt;status_message = <span class="string">"状态变更为未匹配状态"</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">if</span> ($snapshot-&gt;is_error) &#123;</span><br><span class="line">                    <span class="comment">// 1</span></span><br><span class="line">                    $snapshot-&gt;status_text = <span class="string">"请求错误"</span>;</span><br><span class="line">                    $snapshot-&gt;status_level = <span class="number">2</span>;</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    <span class="comment">// 2、5</span></span><br><span class="line">                    $snapshot-&gt;status_text = <span class="string">"匹配命中"</span>;</span><br><span class="line">                    $snapshot-&gt;status_level = <span class="number">1</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 错误则未完成</span></span><br><span class="line">        $snapshot-&gt;is_done = <span class="keyword">true</span>;</span><br><span class="line">	    $snapshot-&gt;saveOrFail();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> $monitor Monitor</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> $snapshot Snapshot</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">updateMonitorData</span><span class="params">($monitor, $snapshot)</span></span>&#123;</span><br><span class="line">	    $monitorData = $monitor-&gt;data;</span><br><span class="line">	    $monitorData-&gt;last_error = $snapshot-&gt;is_error;</span><br><span class="line">	    $monitorData-&gt;last_match = $snapshot-&gt;is_match;</span><br><span class="line">        $monitorData-&gt;last_status_level = $snapshot-&gt;status_level;</span><br><span class="line">        $monitorData-&gt;last_status_text = $snapshot-&gt;status_text;</span><br><span class="line"></span><br><span class="line">	    $nowTime = Carbon::now();</span><br><span class="line"></span><br><span class="line">	    <span class="keyword">if</span> ($monitorData-&gt;last_error) &#123;</span><br><span class="line">		    $monitorData-&gt;last_error_time = $nowTime;</span><br><span class="line">	    &#125;</span><br><span class="line">	    <span class="keyword">if</span> ($monitorData-&gt;last_match) &#123;</span><br><span class="line">		    $monitorData-&gt;last_match_time = $nowTime;</span><br><span class="line">	    &#125;</span><br><span class="line"></span><br><span class="line">	    <span class="comment">// 至少30秒更新一次内容，不足30秒不更新</span></span><br><span class="line">        <span class="keyword">if</span> ($monitorData-&gt;last_request_time === <span class="keyword">null</span> || $monitorData-&gt;last_request_time-&gt;diffInSeconds($nowTime) &gt;= <span class="number">30</span>)&#123;</span><br><span class="line">            $monitorData-&gt;time_total_average_1hour = $monitor-&gt;snapshots()-&gt;whereIsDone(<span class="number">1</span>)-&gt;where(<span class="string">'created_at'</span>, <span class="string">'&gt;'</span>, Carbon::now()-&gt;subHour(<span class="number">1</span>))-&gt;avg(<span class="string">'time_total'</span>);</span><br><span class="line">            $monitorData-&gt;last_1hour_table_cache = json_encode($monitor-&gt;flotData());</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        $monitorData-&gt;last_request_time = $nowTime;</span><br><span class="line"></span><br><span class="line">	    $monitorData-&gt;saveOrFail();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 决定要不要通知，包括通知文本的生成都在这里</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> Snapshot $snapshot</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">handleSnapshotNotice</span><span class="params">(Snapshot $snapshot)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (!$snapshot-&gt;is_notice)&#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> ($snapshot-&gt;monitor-&gt;no_notice_error &amp;&amp; ($snapshot-&gt;status_text == <span class="string">"请求错误"</span> || $snapshot-&gt;status_text == <span class="string">"错误恢复"</span>))&#123;</span><br><span class="line">            <span class="keyword">return</span> ;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> ($snapshot-&gt;monitor-&gt;no_notice_match &amp;&amp; ($snapshot-&gt;status_text == <span class="string">"匹配命中"</span> || $snapshot-&gt;status_text == <span class="string">"未匹配"</span>))&#123;</span><br><span class="line">            <span class="keyword">return</span> ;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">/** <span class="doctag">@var</span> User $user */</span></span><br><span class="line">        $user = User::findOrFail($snapshot-&gt;monitor-&gt;project-&gt;user_id);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        \Mail::to($user)-&gt;send(<span class="keyword">new</span> MonitorNotice($snapshot));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>MonitorJob：<br><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">namespace</span> <span class="title">App</span>\<span class="title">Jobs</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">use</span> <span class="title">App</span>\<span class="title">Monitor</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">App</span>\<span class="title">Service</span>\<span class="title">MonitorService</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">App</span>\<span class="title">Service</span>\<span class="title">SnapshotService</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">Illuminate</span>\<span class="title">Bus</span>\<span class="title">Queueable</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">Illuminate</span>\<span class="title">Queue</span>\<span class="title">SerializesModels</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">Illuminate</span>\<span class="title">Queue</span>\<span class="title">InteractsWithQueue</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">Illuminate</span>\<span class="title">Contracts</span>\<span class="title">Queue</span>\<span class="title">ShouldQueue</span>;</span><br><span class="line"><span class="keyword">use</span> <span class="title">Illuminate</span>\<span class="title">Foundation</span>\<span class="title">Bus</span>\<span class="title">Dispatchable</span>;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MonitorJob</span> <span class="keyword">implements</span> <span class="title">ShouldQueue</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="keyword">use</span> <span class="title">Dispatchable</span>, <span class="title">InteractsWithQueue</span>, <span class="title">Queueable</span>, <span class="title">SerializesModels</span>;</span><br><span class="line">    <span class="keyword">protected</span> $monitor;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Create a new job instance.</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> Monitor $monitor</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">__construct</span><span class="params">(Monitor $monitor)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">$this</span>-&gt;monitor = $monitor;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Execute the job.</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> void</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">handle</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">$this</span>-&gt;monitor-&gt;is_enable===<span class="keyword">false</span>)&#123;</span><br><span class="line">        	\MonitorLog::info(<span class="string">"未启用的监控：ID[&#123;$this-&gt;monitor-&gt;id&#125;], 跳过执行并再进入队列"</span>);</span><br><span class="line">            MonitorService::joinQueue(<span class="keyword">$this</span>-&gt;monitor);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">	    \MonitorLog::debug(<span class="string">"队列：监控ID[&#123;$this-&gt;monitor-&gt;id&#125;]，标题[&#123;$this-&gt;monitor-&gt;title&#125;]"</span>);</span><br><span class="line"></span><br><span class="line">	    $snapshot = SnapshotService::createSnapshot([<span class="string">'monitor_id'</span>=&gt;<span class="keyword">$this</span>-&gt;monitor-&gt;id]);</span><br><span class="line"></span><br><span class="line">	    $requestResult = MonitorService::request(<span class="keyword">$this</span>-&gt;monitor);</span><br><span class="line"></span><br><span class="line">	    MonitorService::storeSnapshot($snapshot, $requestResult);</span><br><span class="line"></span><br><span class="line">	    MonitorService::updateMonitorData(<span class="keyword">$this</span>-&gt;monitor, $snapshot);</span><br><span class="line"></span><br><span class="line">        MonitorService::handleSnapshotNotice($snapshot);</span><br><span class="line"></span><br><span class="line">        MonitorService::joinQueue(<span class="keyword">$this</span>-&gt;monitor);</span><br><span class="line"></span><br><span class="line">	    \MonitorLog::debug(<span class="string">"队列：监控ID[&#123;$this-&gt;monitor-&gt;id&#125;]"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>开源项目地址：<a href="https://github.com/shellus/SiteMonitor" target="_blank" rel="noopener">https://github.com/shellus/SiteMonitor</a></p>

      
    </div>

    

    
    
    
<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">------本文结束<i class="fa fa-paw"></i>感谢阅读------</div>
    
</div>
  
</div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欣赏此文？求鼓励，求支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.png" alt="云舒 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="云舒 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>云舒</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.yunshu168.com/posts/6ca2fd60.html" title="使用laravel开发网站监控程序">http://blog.yunshu168.com/posts/6ca2fd60.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/监控/" rel="tag"># 监控</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/fab40788.html" rel="next" title="数据库备份脚本">
                <i class="fa fa-chevron-left"></i> 数据库备份脚本
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/8aff0860.html" rel="prev" title="JWT 介绍">
                JWT 介绍 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      
        <div id="gitment-container"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="云舒" />
            
              <p class="site-author-name" itemprop="name">云舒</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives">
                
                    <span class="site-state-item-count">68</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">5</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">28</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/yunshu2009" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:yunshu.luo@gmail.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.cnblogs.com/luoyunshu/" target="_blank" title="Cnblogs"><i class="fa fa-fw fa-globe"></i>Cnblogs</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.bilibili.com" target="_blank" title="bilibili"><i class="fa fa-fw fa-globe"></i>bilibili</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#设计思路"><span class="nav-number">1.</span> <span class="nav-text">设计思路</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#程序实现"><span class="nav-number">2.</span> <span class="nav-text">程序实现</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#数据库表设计"><span class="nav-number">2.1.</span> <span class="nav-text">数据库表设计</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#编码实现"><span class="nav-number">2.2.</span> <span class="nav-text">编码实现</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2012 &mdash; <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">云舒</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Pisces</a></div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.4"></script>



  



	





  





  






<!-- LOCAL: You can save these files to your site and update links -->
    
        
         <!-- <link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css"> -->
        <!-- <script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script> -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/theme-next/theme-next-gitment@1/default.css">
        <script src="https://cdn.jsdelivr.net/gh/theme-next/theme-next-gitment@1/gitment.browser.js"></script>
    
<!-- END LOCAL -->

    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitment({
            id: decodeURI(window.location.pathname),
            owner: 'yunshu2009',
            repo: 'yunshu2009.github.io',
            
            oauth: {
            
            
                client_secret: '15cdd9dc30fb9e0c97260bf79fe09d158fa04b22',
            
                client_id: '9495da16cda475a5e221'
            }});
        gitment.render('gitment-container');
      }

      
      renderGitment();
      
      </script>
    






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  


</body>
</html>
